import {
  login,
  getInfo,
  loginCode
} from '@/api/login'
import {
  getAreaList
} from '@/api/public'
import {
  getUserAuthority
} from "@/api/set";
import {
  Message
} from 'element-ui';
import {
  setRoleRoute,
  resetRouter
} from "@/router/routerConfig";
import {
  setConfig,
  getConfig,
  setUserInfo,
  getToken,
  setToken,
  removeToken,
  setUserId,
  getOfficesList as getLocalOfficesList,
  setOfficesList,
  setRole
} from "@/utils/auth";
import {
  getGlobalConfig
} from '@/api/public';
const user = {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {},
    avatar: require('@/assets/images/avatar.png'),
    roles: [],
    permissions: [],
    refreshMainKey: true,
    branchOffices: {},
    roleRouter: null, //当前角色权限路由
  },

  mutations: {
    // SET_TOKEN: (state, token) => {
    //   state.token = token
    // },
    // SET_USER_ID: (state, id) => {
    //   state.id = id
    // },
    SET_USERINFO: (state, info) => {
      state.userInfo = info
      setUserInfo(info)
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_REFRESH_MAIN: (state, data) => {
      //让key改变,来刷新app-mian
      state.refreshMainKey = data;
    },
    SET_ROLEROUTER: (state, data) => {
      state.roleRouter = data;
    },
    SET_GLOBAL_CONFIG: (state, globalConfig) => {
      state.globalConfig = globalConfig;
      setConfig(globalConfig);
    },
  },

  actions: {
    //存储角色权限路由
    setRoleRouter({
      commit
    }, data) {
      return new Promise((resolve) => {
        getUserAuthority().then(res => {
          if (res.code == 200) {
            commit("SET_ROLEROUTER", JSON.parse(res.data.admin_role));
          }
          resolve();
        })
      })
    },
    // 登录
    Login({
      commit
    }, userInfo) {
      const phone = userInfo.phone.trim()
      const password = userInfo.password;
      const code = userInfo.code;
      const loginType = userInfo.loginType;
      return new Promise((resolve, reject) => {
        if (loginType == 1) {
          //账号密码登录
          login({
            phone,
            password
          }).then(async (res) => {
            if (res.code == 200) {
              setToken(res.data.token)
              setUserId(res.data.user_id)
              setUserInfo(res.data);
              setRole(res.data.level);
              await setRoleRoute(); //获取用户权限路由并设置
              // commit('SET_TOKEN', res.data.token)
              // commit('SET_USER_ID', res.data.user_id)
              resolve({
                code: 200,
                msg: res.msg
              })
            } else {
              // Message.error(res.msg);
              resolve(res)
            }
          }).catch(error => {
            reject(error)
          })
        } else {
          //短信验证码登录
          loginCode({
            phone: username,
            code
          }).then(async (res) => {
            if (res.code == 200) {
              setToken(res.data.token)
              setUserId(res.data.user_id)
              setUserInfo(res.data);
              setRole(res.data.level);
              await setRoleRoute(); //获取用户权限路由并设置
              // commit('SET_TOKEN', res.data.token)
              // commit('SET_USER_ID', res.data.user_id)
              resolve({
                code: 200,
                msg: res.msg
              })
            } else {
              // Message.error(res.msg);
              resolve(res)
            }
          })
        }

      })
    },

    DingLogin({
      commit
    }, res) {
      return new Promise(async (resolve, reject) => {
        if (res.code == 200) {
          setToken(res.data.token)
          setUserId(res.data.user_id);
          setUserInfo(res.data);
          setRole(res.data.level);
          await setRoleRoute();
          // commit('SET_TOKEN', res.data.token)
          // commit('SET_USER_ID', res.data.user_id)
        }
        resolve(res)
      })

    },

    // 获取用户信息
    GetInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          const user = res.user
          const avatar = (user.avatar == "" || user.avatar == null) ? require("@/assets/images/profile.jpg") : process.env.VUE_APP_BASE_API + user.avatar;
          if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', res.roles)
            commit('SET_PERMISSIONS', res.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_ID', user.userId)
          commit('SET_NAME', user.userName)
          commit('SET_AVATAR', avatar)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    setGlobalConfig({
      commit
    }) {
      return new Promise((resolve, reject) => {
        if (getConfig()) {
          //存在全局数据 不重复请求
          resolve({
            code: 200
          })
        } else {
          getGlobalConfig().then(res => {
            if (res.code == 200) {
              commit('SET_GLOBAL_CONFIG', res.data)
              resolve({
                code: 200
              });
            } else {
              resolve({
                code: 0
              });
            }
          }).catch(error => {
            resolve(error)
          })
        }

      })
    },
    // 退出系统
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        localStorage.clear();
        resolve();
        setTimeout(() => {
          location.reload();
        }, 0)
      })
    },

    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },
    //刷新Main区域
    refreshMain({
      commit
    }, data) {
      return new Promise((resolve) => {
        commit("SET_REFRESH_MAIN", data)
        resolve();
      })
    },

    GetOfficesList() {
      return new Promise((resolve, reject) => {
        if (getLocalOfficesList()) {
          resolve({
            code: 200
          });
        } else {
          getAreaList().then((res) => {
            if (res.code == 200) {
              setOfficesList(JSON.stringify(res.data));
              resolve({
                code: 200
              })
            } else {
              resolve({
                code: 200
              })
            }
          }).catch(err => {
            resolve(error)
          })
        }
      })
    },
  }
}

export default user;